import { useEffect, useRef, useState } from 'react';
import { Button, Cascader, Checkbox, Form, Input, Modal, Radio, Upload, UploadFile, Image, InputNumber, message, DatePicker } from 'antd';
import { useModel, Access } from '@umijs/max'
import { 
  StationDevice, StationGround, StationParkType, StationStatus, editStation,
  getStationInfo, searchRegion, geocoder,
} from './services'
import { useRequest } from 'ahooks';
import { PlusOutlined } from '@ant-design/icons';
import { styled } from '@umijs/max'
import useTencentMap from '@/components/useTencentMap'
import { Card } from '@/components/Card';
import OpeningHours from './components/OpeningHours';
import dayjs, { Dayjs } from 'dayjs';
import { enum2options } from '@/utils/enum2options';
import { SUCCESS_CODE } from '@/constants';
import { queryCityOptions2 } from '@/services/common';
import OrgSelect from '@/components/OrgSelect';
import ManagerInfo from './components/ManagerInfo';
import CityMSelect from '@/components/CityMSelect';
import UserSelect from '@/components/UserSelect';
const MapContainer = styled.div`
  width: 100%;
  height: 240px;
  display: flex;
  gap: 16px;

  .map-content {
    width: 740px;
    height: 100%;
    border-radius: 6px;
    flex-shrink: 0;
    overflow: hidden;
  }

  .map-list {
    flex: 1;
    height: 100%;
    overflow-y: auto;
    border: 1px solid #bbbbbb;
    border-radius: 6px;
    padding: 8px 12px;
    display: flex;
    flex-direction: column;
    gap: 8px;

    .map-item {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      cursor: pointer;
      padding: 6px 10px;
      border: 1px solid #eee;
      border-radius: 6px;
      flex-shrink: 0;
    }
  }
`

const LatLngContainer = styled.div`
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;

  .label {
    height: var(--ant-form-label-height);
    color: var(--ant-form-label-color);
    font-size: var(--ant-form-label-font-size);
    display: flex;
    align-items: center;
    margin-left: 16px;

    &::before {
      content: '*';
      color: var(--ant-form-label-required-mark-color);
      font-size: var(--ant-font-size);
      font-family: SimSun,sans-serif;
      padding-right: 4px;
    }

    &::after {
      content: ':';
      padding-left: 2px;
      padding-right: 8px;
    }
  }
`

const DeviceLabel = styled.div`
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
  justify-content: center;

  img {
    width: 18px;
    height: 18px;
  }
`

let markerClick = false

const DeviceOptions = [
  {label: <DeviceLabel><img src={`https://homechargesmall.liaoqianapp.com/img/device-icon-${StationDevice.便利店}.png`} /><span>便利店</span></DeviceLabel>, value: StationDevice.便利店},
  {label: <DeviceLabel><img src={`https://homechargesmall.liaoqianapp.com/img/device-icon-${StationDevice.餐饮}.png`} /><span>餐饮</span></DeviceLabel>, value: StationDevice.餐饮},
  {label: <DeviceLabel><img src={`https://homechargesmall.liaoqianapp.com/img/device-icon-${StationDevice.卫生间}.png`} /><span>卫生间</span></DeviceLabel>, value: StationDevice.卫生间},
  {label: <DeviceLabel><img src={`https://homechargesmall.liaoqianapp.com/img/device-icon-${StationDevice.休息室}.png`} /><span>休息室</span></DeviceLabel>, value: StationDevice.休息室},
  {label: <DeviceLabel><img src={`https://homechargesmall.liaoqianapp.com/img/device-icon-${StationDevice.雨棚}.png`} /><span>雨棚</span></DeviceLabel>, value: StationDevice.雨棚},
  {label: <DeviceLabel><img src={`https://homechargesmall.liaoqianapp.com/img/device-icon-${StationDevice.有人值守}.png`} /><span>有人值守</span></DeviceLabel>, value: StationDevice.有人值守},
]

type WxSearchResult = {
  address: string
  location: {
    lat: number
    lng: number
  }
}

const managerInfoValidator = (value: Record<string, string>) => {
  const keys = Object.keys(value || {})
  if (keys.length && !keys.at(-1)?.endsWith('23:59')) {
    return Promise.reject(new Error('尚有剩余可分配时间，请继续添加联系方式'))
  }
  return Promise.resolve()
}

const RoleEditPage: React.FC<RoutePageProps> = (props) => {
  const [editForm] = Form.useForm()
  const { runAsync, loading } = useRequest(editStation, {manual: true})
  const { data: stationInfo, runAsync: getData } = useRequest(getStationInfo, {manual: true})
  const { closeCurrentTab } = useModel('global')
  const [editable, setEditable] = useState(false)
  const tencentMap = useTencentMap('mapContainer')
  const marker = useRef<any>()
  const getGeocoder = useRequest(geocoder, {manual: true})
  const tencentReq = useRequest(searchRegion, {manual: true, debounceWait: 200})
  const keyword = useRef<string>('')
  const cityOptions = useRequest(queryCityOptions2)
  const [cityName, setCityName] = useState<string>()
  const [addressList, setAddressList] = useState<WxSearchResult[]>([])
  const [imgList, setImgList] = useState<string[]>([])
  const [previewCurrent, setPreviewCurrent] = useState(0)
  const imageList = Form.useWatch('imgs', editForm)

  const onFinish = (formValues: any) => {
    const imgs = formValues.imgs?.filter((item: any) => item.status === 'done').map((item: any) => item.url).join(',')
    // const serviceTime = formValues.serviceTime.map((item: [Dayjs, Dayjs]) => {
    //   const [startTime, endTime] = item
    //   return `${startTime.format('HH:mm')}-${endTime.format('HH:mm')}`
    // }).join(',')
    let openTime: any = {
      openType: formValues.openTime,
      online: true,
      timeList: [],
    }
    if (stationInfo?.data.openTime) {
      const oldOpenTime = JSON.parse(stationInfo?.data.openTime)
      if (openTime.openType === oldOpenTime.openType) {
        openTime = oldOpenTime
      }
    }
    runAsync({
      stationName: formValues.stationName,
      inviteCode: formValues.inviteCode,
      networkFee: formValues.networkFee,
      platRate:formValues.platRate,
      networkDay: formValues.networkDay.format('YYYY-MM-DD'),
      ownerId: formValues.ownerId.id,
      openTime: JSON.stringify(openTime),
      electricType: formValues.electricType,
      shareIn: formValues.shareIn,
      imgs,
      orgId: formValues.org?.id,
      orgName: formValues.org?.name,
      cityId: formValues.cascader[2],
      address: formValues.address,
      longitude: formValues.longitude,
      latitude: formValues.latitude,
      // serviceTime: serviceTime,
      notice: formValues.notice,
      deviceList: formValues.deviceList?.join(','),
      parkType: formValues.parkType,
      parkInfo: formValues.parkInfo,
      ground: formValues.ground,
      stationInfo: formValues.stationInfo,
      status: formValues.status,
      fromType: 1,
      id: stationInfo?.data.id,
      managerInfo: formValues.managerInfo ? JSON.stringify(formValues.managerInfo) : '',
      otherTel: formValues.otherTel ? JSON.stringify(formValues.otherTel) : '',
      ownerType: 1,
    })
    .then(() => {
      const event = new CustomEvent('refreshShareStationList')
      window.dispatchEvent(event)
      closeCurrentTab('/station/shareStationList')
    })
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  }

  // const setMapMarker = (options: {position: {lat: number, lng: number}, properties: Record<string, string>}[]) => {
  //   marker.current.updateGeometries(options)
  // }

  const reSetMapMarker = (options: {position: {lat: number, lng: number}, properties: Record<string, string>}[]) => {
    marker.current.setGeometries(options)
    tencentMap.setCenter(new window.TMap.LatLng(options[0].position.lat, options[0].position.lng))
  }

  const onCityChange = (value: any, item: any) => {
    if (item.length) {
      setCityName(item[2].label)
    }
  }

  const onAddressChose = (address: WxSearchResult) => {
    editForm.setFieldsValue({
      longitude: address.location.lng,
      latitude: address.location.lat,
      address: address.address,
    })
    reSetMapMarker([{
      position: new window.TMap.LatLng(address.location.lat, address.location.lng),
      properties: {
        address: address.address,
      }
    }])
  }

  const onSearch = () => {
    if (!cityName) {
      Modal.warn({
        title: '提示',
        content: '请先选择所在城市',
      })
      return
    }
    if (!keyword.current) {
      Modal.warn({
        title: '提示',
        content: '请输入要搜索的地址',
      })
      return
    }
    tencentReq.runAsync({
      title: keyword.current,
      cityId: cityName,
    }).then((res: any) => {
      const result = JSON.parse(res.data)
      if (result.status === 0) {
        if (result.data.length) {
          setAddressList(result.data)
          // reSetMapMarker(result.data.map((it: any) => ({
          //   position: new window.TMap.LatLng(it.location.lat, it.location.lng),
          //   properties: {
          //     address: it.address
          //   }
          // })))
          // const firstLatLng = result.data[0].location
          // tencentMap.setCenter(new window.TMap.LatLng(firstLatLng.lat, firstLatLng.lng))
        } else {
          Modal.warn({
            content: '未查询到相关地址',
          })
        }
      } else {
        Modal.error({
          title: '错误',
          content: result.message,
        })
      }
    })
  }

  const onFileUpLoadChange = (file: UploadFile) => {
    const { status, response, uid } = file
    if (status === 'done' && response) {
      const imgs = editForm.getFieldValue('imgs')
      const { code, data, text } = response
      if (code === SUCCESS_CODE) {
        editForm.setFieldsValue({
          imgs: imgs.map((item: any) => {
            if (item.uid === uid) return {
              status: 'done', url: data
            }
            return item
          })
        })
      } else {
        Modal.error({
          title: '错误',
          content: text === '上传文件过大' ? '文件体积超过 2M，请重新上传' : '图片上传失败，请重试',
        })
        editForm.setFieldsValue({
          imgs: imgs.filter((item: any) => item.uid !== uid)
        })
      }
    } else if (status === 'error') {
      const imgs = editForm.getFieldValue('imgs')
      editForm.setFieldsValue({
        imgs: imgs.filter((item: any) => item.uid !== uid)
      })
    }
  }

  const openPreview = (file: UploadFile) => {
    const index = imageList.findIndex((item: UploadFile) => item.uid === file.uid)
    setPreviewCurrent(index)
    setImgList(imageList.map((item: UploadFile) => item.url!))
  }

  useEffect(() => {
    if (!!stationInfo && !!cityOptions.data) {
      const { data: { cityId } } = stationInfo
      const { data: _option } = cityOptions.data
      const provinceCode = `${cityId.substring(0, 2)}0000`
      const cityCode = `${cityId.substring(0, 4)}00`
      const areaCode = cityId
      const cityList = _option.find(it => it.value === provinceCode)?.children
      if (cityList?.length) {
        const areaList = cityList.find(it => it.value === cityCode)?.children
        if (areaList?.length) {
          const area = areaList.find(it => it.value === areaCode)
          setCityName(area?.label)
        }
      }
    }
  }, [stationInfo, cityOptions.data])

  useEffect(() => {
    if (props.params.id) {
      getData({stubGroupId: props.params.id})
      .then(res => {
        const { data } = res
        const cascaderValue = [`${data.cityId.substring(0, 2)}0000`, `${data.cityId.substring(0, 4)}00`, data.cityId]
        const openTime = JSON.parse(data.openTime)
        editForm.setFieldsValue({
          stationName: data.stationName,
          inviteCode: data.inviteCode,
          networkFee: data.networkFee,
          platRate:data.platRate,
          networkDay: dayjs(data.networkDay),
          ownerId: {
            id: data.ownerId,
            name: data.ownerName,
          },
          openTime: openTime.openType,
          electricType: data.electricType,
          shareIn: data.shareIn,
          org: data.orgId ? {
            id: data.orgId,
            name: data.orgName,
          } : undefined,
          imgs: data.imgs.split(',').map(it => ({status: 'done', url: it})),
          cascader: cascaderValue,
          address: data.address,
          longitude: data.longitude,
          latitude: data.latitude,
          // serviceTime: data.serviceTime.split(',').map(item => {
          //   const times = item.split('-')
          //   return [dayjs(times[0], 'HH:mm'), dayjs(times[1], 'HH:mm')]
          // }),
          notice: data.notice,
          deviceList: data.deviceList ? data.deviceList.split(',').map(it => parseInt(it)) : [],
          parkType: data.parkType,
          parkInfo: data.parkInfo,
          ground: data.ground,
          stationInfo: data.stationInfo,
          status: data.status,
          managerInfo: data.managerInfo ? JSON.parse(data.managerInfo) : undefined,
          otherTel: data.otherTel ? JSON.parse(data.otherTel) : undefined,
        })
      })
    } else {
      editForm.setFieldsValue({
        stationName: undefined,
        inviteCode: undefined,
        networkFee: undefined,
        networkDay: undefined,
        platRate:undefined,
        ownerId: undefined,
        openTime: '手动上下线',
        electricType: 1,
        shareIn: 1,
        org: undefined,
        cascader: undefined,
        imgs: undefined,
        address: undefined,
        longitude: undefined,
        latitude: undefined,
        // serviceTime: [[dayjs().set('hour', 0).set('minute', 0), dayjs().set('hour', 23).set('minute', 59)]],
        notice: undefined,
        deviceList: undefined,
        parkType: StationParkType.免费,
        parkInfo: undefined,
        ground: StationGround.地上,
        stationInfo: undefined,
        status: StationStatus.运营中,
      })
    }
    setEditable(props.params.type === 'edit')
  }, [props.params.id, props.params.type])

  useEffect(() => {
    if (stationInfo && tencentMap && marker.current) {
      const data = stationInfo.data
      reSetMapMarker([{
        position: new window.TMap.LatLng(data.latitude, data.longitude),
        properties: {
          address: data.address,
        }
      }])
      tencentMap.setCenter(new window.TMap.LatLng(data.latitude, data.longitude))
    }
  }, [stationInfo, marker.current])

  useEffect(() => {
    if (tencentMap) {
      // 注册地图点击事件
      tencentMap.on('click', (res: any) => {
        if (markerClick) {
          markerClick = false
          return
        }
        editForm.setFieldsValue({
          longitude: res.latLng.lng,
          latitude: res.latLng.lat,
        })
        // getGeocoder.runAsync({
        //   locX: res.latLng.lng,
        //   locY: res.latLng.lat,
        // }).then((_res: any) => {
        //   const result = JSON.parse(_res.data)
        //   if (result.status === 0) {
        //     editForm.setFieldsValue({
        //       longitude: result.result.location.lng,
        //       latitude: result.result.location.lat,
        //       address: result.result.address,
        //     })
        //     reSetMapMarker([{
        //       position: new window.TMap.LatLng(res.latLng.lat, res.latLng.lng),
        //       properties: {
        //         address: result.result.address
        //       }
        //     }])
        //   } else {
        //     Modal.error({
        //       title: '错误',
        //       content: result.message,
        //     })
        //   }
        // })
      })
      // 创建一个位于地图中心点的marker
			marker.current = new window.TMap.MultiMarker({
				map: tencentMap,
				geometries: [],
			})
      // marker.current.on('click', (res: any) => {
      //   markerClick = true
      //   const { position, properties } = res.geometry
      //   editForm.setFieldsValue({
      //     longitude: parseFloat(position.lng.toFixed(6)),
      //     latitude: parseFloat(position.lat.toFixed(6)),
      //     address: properties.address,
      //   })
      // })
      const center = tencentMap.getCenter()
      reSetMapMarker([{
        position: new window.TMap.LatLng(center.lat, center.lng),
        properties: {
          address: ''
        }
      }])
    }
  }, [tencentMap])
  
  return (
    <div className='container'>
      <Card>
        <Form form={editForm} name='editForm' labelCol={{flex: '120px'}} onFinish={onFinish}>
          <Form.Item name='stationName' label='场站名称' rules={[{required: true, message: '请输入场站名称'}]}>
            <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
          </Form.Item>
          <Form.Item  name='inviteCode' label='推荐码' hidden={stationInfo !== null && stationInfo !== undefined}>
            <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
          </Form.Item>
          <Form.Item name='networkFee' label='扣除流量费金额' rules={[{required: true, message: '请输入扣除流量费金额'}]}>
            <InputNumber placeholder='请输入' style={{width: 320}} disabled={!editable} addonAfter='元' />
          </Form.Item>
          <Form.Item name='platRate' label='平台抽成比例' rules={[{required: true, message: '请输入平台抽成比例'}]}>
            <InputNumber placeholder='请输入0-100' style={{width: 320}} disabled={!editable} addonAfter='%' />
          </Form.Item>
          <Form.Item name='networkDay' label='流量费开始收费时间' rules={[{required: true, message: '请选择开始收费时间'}]}>
            <DatePicker placeholder='请选择' />
          </Form.Item>
          <Form.Item name='org' label='城市经理人'>
            <CityMSelect style={{width: 320}} allowClear />
          </Form.Item>
          <Form.Item name='ownerId' label='私桩主' rules={[{required: true, message: '请选择私桩主'}]}>
            <UserSelect style={{width: 320}} allowClear />
          </Form.Item>
          <Form.Item name='openTime' label='开放模式' required hidden={stationInfo !== null && stationInfo !== undefined}>
            <Radio.Group options={[
              {label: '手动上下线', value: '手动上下线'},
              {label: '自定义开放时间', value: '自定义开放时间'},
            ]} />
          </Form.Item>
          <Form.Item name='electricType' label='电费账户模式' required>
            <Radio.Group options={[
              {label: '平台收取', value: 1},
              {label: '平台不收取', value: 2},
            ]} />
          </Form.Item>
          <Form.Item name='shareIn' label='桩主共享优惠' required>
            <Radio.Group options={[
              {label: '参与', value: 1},
              {label: '不参与', value: 2},
            ]} />
          </Form.Item>
          <Form.Item name='status' label='场站状态' required>
            <Radio.Group options={[
              {label: '建设中', value: StationStatus.建设中},
              {label: '运营中', value: StationStatus.运营中},
              {label: '暂停运营', value: StationStatus.暂停运营},
            ]} />
          </Form.Item>
          <Form.Item name='ground' label='停车场类型' required>
            <Radio.Group options={enum2options(StationGround)} />
          </Form.Item>
          <Form.Item label='场站图片' >
            <Form.Item
              name='imgs' noStyle
              valuePropName="fileList" getValueFromEvent={normFile}
            >
              <Upload 
                action="/app/user/fileUp" listType="picture-card" disabled={!editable}
                data={{type: 1}} maxCount={8}
                headers={{Authorization: localStorage.Authorization}}
                onChange={({file}) => onFileUpLoadChange(file)}
                onPreview={openPreview}
              >
                {
                  !imageList || imageList.length < 8 ? <button style={{ border: 0, background: 'none' }} type="button">
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>选择照片</div>
                  </button> : null
                }
              </Upload>
            </Form.Item>
            <div>
              提示：上传图片体积不超过2M，最多可上传8张图片
            </div>
          </Form.Item>
          <Form.Item name='stationInfo' label='场站介绍' rules={[{required: true, message: '请输入场站介绍'}]}>
            <Input.TextArea placeholder='请输入' style={{width: 320, height: 80}} />
          </Form.Item>
          <Form.Item name='cascader' label='所在城市' rules={[{required: true, message: '请选择所在城市'}]}>
            <Cascader
              loading={cityOptions.loading}
              options={cityOptions.data?.data}
              style={{width: 320}}
              disabled={!editable}
              placeholder='请选择'
              onChange={onCityChange}
            />
          </Form.Item>
          <Form.Item label=' ' colon={false}>
            <LatLngContainer>
              <Input style={{width: 390}} placeholder='请输入要搜索的地址' onChange={({target}) => keyword.current = target.value} />
              <Button type='primary' style={{marginLeft: 16}} onClick={onSearch} loading={tencentReq.loading}>查询</Button>
            </LatLngContainer>
          </Form.Item>
          <Form.Item label=' ' colon={false}>
            <MapContainer>
              <div id='mapContainer' className="map-content"></div>
              <Access accessible={addressList.length > 0}>
                <div className="map-list">
                  {
                    addressList.map((it, idx) => <div className='map-item' key={idx} onClick={() => onAddressChose(it)}>
                      {it.address}
                    </div>)
                  }
                </div>
              </Access>
            </MapContainer>
          </Form.Item>
          <Form.Item label='经度' required>
            <LatLngContainer>
              <Form.Item name='longitude' rules={[{required: true, message: '请选择经纬度'}]} noStyle>
                <InputNumber placeholder='请输入' controls={false} style={{width: 200}} />
              </Form.Item>
              <div className='label'>纬度</div>
              <Form.Item name='latitude' noStyle>
                <InputNumber placeholder='请输入' controls={false} style={{width: 200}} />
              </Form.Item>
            </LatLngContainer>
          </Form.Item>
          <Form.Item name='address' label='场站地址' rules={[{required: true, message: '请输入场站地址'}]}>
            <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
          </Form.Item>
          {/*<Form.Item name='serviceTime' label='营业时间' required>*/}
          {/*  <OpeningHours />*/}
          {/*</Form.Item>*/}
          <Form.Item name='notice' label='场站公告'>
            <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
          </Form.Item>
          <Form.Item name='deviceList' label='配套设施'>
            <Checkbox.Group options={DeviceOptions} />
          </Form.Item>
          <Form.Item name='parkType' label='停车费' rules={[{required: true, message: '请选择停车收费类型'}]}>
            <Radio.Group options={enum2options(StationParkType)} />
          </Form.Item>
          <Form.Item label=' ' colon={false} name='parkInfo' required={false} rules={[{required: true, message: '请输入停车费介绍'}]}>
            <Input placeholder='示例: 2小时内停车免费' style={{width: 320}} />
          </Form.Item>
          <Form.Item name='managerInfo' label='平台联系方式' rules={[{validator: (_, val) => managerInfoValidator(val)}]}>
            <ManagerInfo />
          </Form.Item>
          <Form.Item name='otherTel' label='桩主联系方式' rules={[{validator: (_, val) => managerInfoValidator(val)}]}>
            <ManagerInfo />
          </Form.Item>
          <Form.Item label=' ' colon={false}>
            <Button type='primary' htmlType='submit' loading={loading}>提交</Button>
          </Form.Item>
        </Form>
      </Card>
      <Image.PreviewGroup
        items={imgList}
        preview={{
          visible: imgList.length > 0,
          current: previewCurrent,
          onChange: (val) => {
            setPreviewCurrent(val)
          },
          onVisibleChange: (val) => {
            if (!val) setImgList([])
          }
        }}
      >
      </Image.PreviewGroup>
    </div>
  );
};

export default RoleEditPage;
